package com.lyon.springboot.util;

import org.springframework.context.ApplicationContext;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class SpringIocUtils {
	private static Map<String, Object> beanFactoryMap =new HashMap<String, Object>();
	@SuppressWarnings({ "unchecked", "hiding" })
	public static <T> T getBean(Class<T> clazz)  {
//		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        if (ConfigUtils.getInstance().flag==false){
            DataSource dataSource = (DataSource)applicationContext.getBean("dataSource");
            ConfigUtils.getInstance().addTableField(dataSource);
            ConfigUtils.getInstance().flag=true;
        }

        String beanName = clazz.getSimpleName().substring(0,1).toLowerCase()+clazz.getSimpleName().substring(1);

		if(beanFactoryMap.containsKey(beanName)){
			return (T)beanFactoryMap.get(beanName);
		}else{
			T t =(T) applicationContext.getBean(beanName);
			beanFactoryMap.put(beanName,t);
			return t;
		}
	}
}
